package com.istock.union.filter;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.istock.union.user.filter.AuthorizationCallback;
import com.istock.union.user.utils.WebCommonUtils;

/**
 * controller的拦截器
 * 
 * 存在一种情况,登录以后,不能访问主页面,需要额外的选择
 * 场景有
 * 1.密码过期,强制修改密码
 * 2.同一个用户,在不同机构/角色下面有不同的菜单权限,需要额外选择机构/角色
 * 
 * AuthorizationInterceptor只做条件判断和页面跳转,对于ssoUser的设置操作,在登录逻辑和点击事件上
 * 
 * 主要拦截所有验证请求中的,对controller的拦截
 * 拦截所有的controller,对登录用户的权限进行赋权和验证
 * 
 * 不检查当前登陆的user是否能满足当前的url
 * @author senvon
 *
 */
public class AuthorizationInterceptor extends HandlerInterceptorAdapter{
	
	@Value("${sso.authorization.ignorRegx}")
	private String ignorRegx = "";
	
	private List<AuthorizationCallback> callBackList;
	public void setCallBackList(List<AuthorizationCallback> callBackList) {
		this.callBackList = callBackList;
	}

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		String url = WebCommonUtils.findAccessPath(request);
		logger.info("AuthorizationInterceptor handle the request:{}",url);
		if(url.matches(ignorRegx)){
			//如果输入的url,可以匹配到忽略的正则表达式,则跳过当前的url访问
			logger.debug("the request url matched with the regx ");
			return true;
		}
		
		//执行配置的callback
		if(callBackList != null) {
			for(AuthorizationCallback callback : callBackList) {
				if(callback.canExecut(request,(HandlerMethod)handler)) {
					boolean result = callback.preCallback(request, response,(HandlerMethod)handler);
					//如果返回false,直接跳出循环,中断后续的执行
					if(!result) {
						return result;
					}
				}
			}
		}
		
		return super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
		
		String url = WebCommonUtils.findAccessPath(request);
		if(url.matches(ignorRegx)){
			return;
		}
		
		//执行配置的callback
		if(callBackList != null) {
			for(AuthorizationCallback callback : callBackList) {
				if(callback.canExecut(request,(HandlerMethod)handler)) {
					boolean result = callback.postCallback(request, response,(HandlerMethod)handler);
					//如果返回false,直接跳出循环,中断后续的执行
					if(!result) {
						return ;
					}
				}
			}
		}
		
		super.postHandle(request, response, handler, modelAndView);
	}
	
	
}
